package controllers

import dao._
import implicits.Implicits._
import io.scalaland.chimney.dsl._
import models.Tables._
import org.joda.time.DateTime
import play.api.mvc.{AbstractController, ControllerComponents}
import shared.pojo.Pojo._
import tool.Tool
import ujson.play.PlayJson
import upickle.default._

import java.io.{ByteArrayInputStream, File}
import javax.imageio.ImageIO
import javax.inject.Inject
import javax.xml.bind.DatatypeConverter
import scala.concurrent.ExecutionContext.Implicits.global

/**
 * Created by Administrator on 2019/8/7
 */
class TestController @Inject()(cc: ControllerComponents)(
  implicit val accountDao: AccountDao,
  implicit val wechatMemberDao: WechatMemberDao,
  implicit val sampleDao: SampleDao,
  implicit val sampleIdDao: SampleIdDao,
  implicit val testDao: TestDao,
  implicit val companyMemberDao: CompanyMemberDao,
) extends
  AbstractController(cc) {

  import test._

  def all = Action.async { implicit request =>
    val data = Tool.transformRq.transform(reader[AccountData])
    companyMemberDao.selectByAccountSome(data.account).flatMap { x =>
      testDao.selectAll(x.companyName).map { x =>
        val array = x.sortBy(_.updateTime).reverse.map { x =>
          writeJs(x)
        }
        Ok(writeJs(array))
      }
    }
  }

  def dbAll = Action.async { implicit request =>
    testDao.selectAll.map { x =>
      val array = x.sortBy(_.updateTime).reverse.map { x =>
        writeJs(x)
      }
      Ok(writeJs(array))
    }
  }

  def getById = Action.async { implicit request =>
    val data = Tool.transformRq.transform(reader[IdData])
    testDao.selectById(data.id).map { x =>
      Ok(writeJs(x))
    }
  }

  def get = Action.async { implicit request =>
    val data = Tool.transformRq.transform(reader[Get.Request])
    val f = if (data.id != 0) {
      testDao.selectById(data.id)
    } else {
      testDao.select(data.sampleId, data.testType, data.company)
    }
    f.map { x =>
      Ok(writeJs(x))
    }
  }

  def updateWorkflow = Action.async(parse.multipartFormData) { implicit request =>
    val data = read[TestInfoData](request.body.dataParts("testData").head)
    testDao.selectById(data.id).flatMap { dbX =>
      val appendIdDir = Tool.getAppendIdDir(data.sampleId, data.id)
      val workflow = data.info.zipWithIndex.map { case (process, curI) =>
        val folder = process.folder
        val trueFolder = if (folder.trim.isEmpty) {
          Tool.getFolder(appendIdDir)
        } else folder
        val appendixDir = new File(appendIdDir, trueFolder).createDirectoryWhenNoExist
        val serverFiles = process.fileNames
        appendixDir.myListFiles.foreach { file =>
          if (!serverFiles.contains(file.getName)) {
            file.deleteQuietly
          }
        }
        val files = Tool.filesMoveDir(s"${curI}", appendixDir)
        val fileNames = files.map(_.getName)
        writeJs(process).toObj ++ ujson.Obj(
          "folder" -> trueFolder,
          "fileNames" -> (process.fileNames ::: fileNames)
        )
      }
      val row = dbX.copy(info = writeJs(workflow), updateTime = new DateTime())
      testDao.update(row).map { x =>
        Ok(ujson.Obj("valid" -> true))
      }
    }
  }


}
